<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <th:block th:insert="~{include :: header('日程安排')}" />
    <link rel="stylesheet" href="/css/font-awesome.min.6.4.css">
    <link rel="stylesheet" href="/css/schedule.css"> 
</head>
<body>
    <div class="container">
        <div class="header">
            <div class="calendar-title" id="current-month-year">2025年10月</div>
            <div class="calendar-controls">
                <button class="control-btn" id="prev-month">上个月</button>
                <button class="control-btn today" id="today-btn">今天</button>
                <button class="control-btn" id="next-month">下个月</button>
            </div>
        </div>
        
        <div class="calendar-weekdays">
            <div class="weekday">周一</div>
            <div class="weekday">周二</div>
            <div class="weekday">周三</div>
            <div class="weekday">周四</div>
            <div class="weekday">周五</div>
            <div class="weekday">周六</div>
            <div class="weekday">周日</div>
        </div>
        
        <div class="calendar-days" id="calendar-days">
            <!-- 日历天数通过JS动态生成 -->
        </div>
        
        <div class="schedule-panel">
            <div class="panel-title" id="selected-date-title">2025年10月5日 的日程</div>
            <div class="schedule-list" id="schedule-list">
                <div class="empty-state">暂无日程安排</div>
            </div>
            <button class="add-btn" onclick="openAddSchedule()">
                <span>+</span> 添加日程
            </button>
        </div>
    </div>
    
    <!-- 日程弹窗 -->
    <div class="modal" id="schedule-modal-list">
        <div class="modal-content">
            <div class="modal-header">
                <div class="modal-title" id="modal-date">2023年10月15日 日程</div>
                <button class="close-btn close-modal" id="close-modal-list">&times;</button>
            </div>
            <div class="modal-body">
                <div class="schedule-list" id="schedule-modal-tab-list">
                    <!-- 日程列表通过JS动态生成 -->
					<div class="empty-schedule">该日期暂无日程安排</div>
                </div>
            </div>
            <div class="modal-footer">
				<button class="add-btn" onclick="closeModalList();openAddSchedule()">
					<span>+</span> 添加日程
				</button>
            </div>
        </div>
    </div>
    
    <!-- 添加/编辑日程模态框 -->
    <div class="modal" id="schedule-modal">
        <div class="modal-content">
            <div class="modal-header">
                <div class="modal-title" id="modal-title">添加日程</div>
                <button class="close-btn close-modal" id="close-modal">&times;</button>
            </div>
            <div class="modal-body">
                <div class="form-row">
                    <div class="form-group">
                        <label for="schedule-date">日期</label>
                        <input type="date" id="schedule-date" class="form-control">
                    </div>
                    <div class="form-group">
                        <label for="schedule-time">时间</label>
                        <input type="time" id="schedule-time" class="form-control">
                    </div>
                </div>
                <div class="form-group">
                    <label for="schedule-content">日程内容</label>
                    <input type="text" id="schedule-content" class="form-control" placeholder="请输入日程内容">
                </div>
                <div class="form-group">
                    <label>
                        <input type="checkbox" id="schedule-important"> 标记为重要日程
                    </label>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-cancel" id="cancel-schedule">取消</button>
                <button class="btn btn-primary" id="save-schedule">保存</button>
            </div>
        </div>
    </div>
    <th:block th:insert="~{include :: footer}" />

    <script th:inline="javascript">
		var issueData = [[${dataMap}]];
		
        // 当前显示的日期和选中的日期
        const today = new Date();
        let currentViewDate = new Date(today.getFullYear(), today.getMonth(), 1); // 当前月份的第一天
        let selectedDate = new Date(today.getFullYear(), today.getMonth(), today.getDate()); // 默认选中当天
        let schedules = JSON.parse(issueData) || {};
        let editingScheduleId = null;
        
        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            renderCalendar(currentViewDate);
            renderSchedules(selectedDate);
            updateSelectedDateTitle();
            
            // 事件监听
            document.getElementById('prev-month').addEventListener('click', prevMonth);
            document.getElementById('next-month').addEventListener('click', nextMonth);
            document.getElementById('today-btn').addEventListener('click', goToToday);
            document.getElementById('close-modal-list').addEventListener('click', closeModalList);
            document.getElementById('close-modal').addEventListener('click', closeModal);
            document.getElementById('cancel-schedule').addEventListener('click', closeModal);
            document.getElementById('save-schedule').addEventListener('click', saveSchedule);
            
            // 点击日历空白处关闭模态框
            document.getElementById('schedule-modal').addEventListener('click', function(e) {
                if (e.target.id === 'schedule-modal') {
                    closeModal();
                }
            });
            // 点击日历空白处关闭模态框
            document.getElementById('schedule-modal-list').addEventListener('click', function(e) {

                if (e.target.id === 'schedule-modal-list') {
                    closeModalList();
                }
            });
        });
        
        // 渲染日历
        function renderCalendar(date) {
            const year = date.getFullYear();
            const month = date.getMonth();
            
            // 更新当前年月显示
            document.getElementById('current-month-year').textContent = `${year}年${month + 1}月`;
            
            // 获取当月第一天和最后一天
            const firstDay = new Date(year, month, 1);
            const lastDay = new Date(year, month + 1, 0);
            const daysInMonth = lastDay.getDate();
            
            // 获取当月第一天是星期几（0-6，0代表星期日）
            // 我们需要调整为周一为第一天，所以将星期日(0)调整为7
            let firstDayOfWeek = firstDay.getDay();
            if (firstDayOfWeek === 0) firstDayOfWeek = 7; // 周日调整为7
            firstDayOfWeek -= 1; // 周一为0索引
            
            // 获取上个月最后几天
            const prevMonthLastDay = new Date(year, month, 0).getDate();
            
            const calendarDays = document.getElementById('calendar-days');
            calendarDays.innerHTML = '';
            
            // 添加上个月最后几天
            for (let i = firstDayOfWeek - 1; i >= 0; i--) {
                const dayElement = createDayElement(prevMonthLastDay - i, true, false, new Date(year, month-1, prevMonthLastDay - i));
                calendarDays.appendChild(dayElement);
            }
            
            // 添加当月天数
            for (let i = 1; i <= daysInMonth; i++) {
                const dayDate = new Date(year, month, i);
                const isToday = isSameDay(dayDate, new Date());
                const isSelected = isSameDay(dayDate, selectedDate);
                
                const dayElement = createDayElement(i, false, isToday, dayDate, isSelected);
                calendarDays.appendChild(dayElement);
            }
            
            // 添加下个月前几天（补全日历网格）
            const totalCells = 42; // 6行×7列
            const nextMonthDays = totalCells - firstDayOfWeek - daysInMonth;
            for (let i = 1; i <= nextMonthDays; i++) {
                const dayElement = createDayElement(i, true, false, new Date(year, month+1, i));
                calendarDays.appendChild(dayElement);
            }
            
            // 渲染所有日期元素的日程标记
            const allDates = [];
            for (let i = 1; i <= daysInMonth; i++) {
                allDates.push(new Date(year, month, i));
            }
            allDates.forEach(date => renderDayEvents(date));
        }
        
        // 创建日期元素
        function createDayElement(dayNumber, isOtherMonth, isToday, date, isSelected = false) {
            const dayElement = document.createElement('div');
            dayElement.className = 'calendar-day';
            
            if (isOtherMonth) {
                dayElement.classList.add('other-month');
            }
            
            if (isToday) {
                dayElement.classList.add('today');
            }
            
            if (isSelected) {
                dayElement.classList.add('selected');
            }
            
            // 获取当日日程数量
            const dateStr = formatDate(date);
            const scheduleCount = schedules[dateStr] ? schedules[dateStr].length : 0;
            // 仅当日程数量大于0时显示
            const scheduleCountHtml = scheduleCount > 0 
                ? `<div class="schedule-count">${scheduleCount}</div>` 
                : '';
            dayElement.innerHTML = `
                <div class="day-number">${dayNumber}</div>
                ${scheduleCountHtml}
                <div class="events-container" id="events-${date.getFullYear()}-${String(date.getMonth()+1).padStart(2, '0')}-${String(dayNumber).padStart(2, '0')}">
                    <!-- 事件将通过JS动态添加 -->
                </div>
            `;
            
            // 点击选择日期
            dayElement.addEventListener('click', function() {
                if (isOtherMonth) {
                    // 如果是补全日期，跳转到补全日期的月份并选中该日期
                    currentViewDate = new Date(date.getFullYear(), date.getMonth(), 1);
                    selectedDate = date;
                    renderCalendar(currentViewDate);
                    renderSchedules(date);
                    updateSelectedDateTitle();
                } else {
                    selectDate(date);
                }
            });
            
            // 添加双击事件
            dayElement.addEventListener('dblclick', function() {
                openScheduleModal(date);
            });
            
            return dayElement;
        }
        
        // 打开日程弹窗
        function openScheduleModal(date) {
            const dateStr = formatDate(date);
            const modal = document.getElementById('schedule-modal-list');
            const modalDate = document.getElementById('modal-date');
            const scheduleList = document.getElementById('schedule-modal-tab-list');
            
            // 设置弹窗标题
            modalDate.textContent = `${date.getFullYear()}年${date.getMonth()+1}月${date.getDate()}日 日程`;
            
            // 清空日程列表
            scheduleList.innerHTML = '';
            // 获取该日期的日程
            const dateSchedules = schedules[dateStr] || [];
            
            if (dateSchedules.length === 0) {
                scheduleList.innerHTML = '<div class="empty-schedule">该日期暂无日程安排</div>';
            } else {
                dateSchedules.forEach((schedule, index) => {
                    const scheduleItem = document.createElement('div');

                    scheduleItem.setAttribute('onclick', '$.modal.openTab("#' + schedule.id + '","/project/issue/' + schedule.id + '")');

                    const priority = schedule.priority;
                    const priorityClass = priority.listClass || 'primary';
                    scheduleItem.className = 'schedule-item borL-' + priorityClass;

                    const issueStatus = schedule.issueStatus;
                    const statusColor = issueStatus ? (issueStatus.htmlColor || 'primary') : 'primary';
                    
                    // 使用 schedule.content 作为默认值，避免 undefined
                    const title = schedule.projectName || '';
                    const content = schedule.subject || '';
                    
                    scheduleItem.innerHTML = `
                        <div class="time">
                            <div class="tracker-name col-${priorityClass}">${schedule.trackerName}#${schedule.id}</div>
                            <div class="badge badge-${statusColor}">${schedule.statusName}</div>
                        </div>
                        <div class="content">
                            <div class="schedule-title">${title}</div>
                            <div class="schedule-content">${content}</div>
                        </div>
                    `;
                    scheduleList.appendChild(scheduleItem);
                });
            }
            
            // 显示弹窗
            modal.style.display = 'flex';
        }
        
        // 渲染日期上的日程标记
        function renderDayEvents(date) {
            const dateStr = formatDate(date);
            const eventsContainer = document.getElementById(`events-${dateStr}`);
            
            if (!eventsContainer) return;

            eventsContainer.innerHTML = '';
            const dateSchedules = schedules[dateStr] || [];
            // 只显示前3个日程
            dateSchedules.slice(0, 3).forEach(schedule => {
                const eventElement = document.createElement('div');
                
                // 区分任务和日程（假设 schedule.type 字段标识类型）
                const statusIcons = {
                    1: '<i class="fas fa-plus-circle"></i>', // 新建
                    2: '<i class="fas fa-spinner"></i>',    // 进行中
                    3: '<i class="fas fa-vial"></i>',      // 待测试
                    4: '<i class="fas fa-check-circle"></i>', // 已解决
                    5: '<i class="fas fa-comment-dots"></i>', // 反馈
                    6: '<i class="fas fa-times-circle"></i>', // 已关闭
                    7: '<i class="fas fa-redo"></i>'       // 重新打开
                };
                const icon = statusIcons[schedule.statusId] || '<i class="fas fa-plus-circle"></i>';
                eventElement.innerHTML = `${icon} ${schedule.subject}`;
                eventElement.title = schedule.projectName + ' ' + schedule.subject;
                eventElement.style.whiteSpace = 'nowrap';
                eventElement.style.overflow = 'hidden';
                eventElement.style.textOverflow = 'ellipsis';
                eventElement.style.width = '114px';

                const issueStatus = schedule.issueStatus;
                const statusColor = issueStatus ? (issueStatus.htmlColor || 'primary') : 'primary';

                eventElement.className = `event-item badge-${statusColor}`;
                
                eventsContainer.appendChild(eventElement);
            });
            
            // 如果日程超过3个，显示更多提示
            if (dateSchedules.length > 3) {
                const moreElement = document.createElement('div');
                moreElement.className = 'event-item';
                moreElement.textContent = `共有${dateSchedules.length}个日程安排`;
                moreElement.style.backgroundColor = '#f1f3f4'; // 更多提示：灰色背景
                moreElement.style.color = '#5f6368'; // 灰色文字
                moreElement.style.width = '114px';
                eventsContainer.appendChild(moreElement);
            }
        }
        
        // 选择日期
        function selectDate(date) {
            selectedDate = date;
            renderCalendar(currentViewDate);
            renderSchedules(date);
            updateSelectedDateTitle();
        }
        
        // 更新选中日期的标题
        function updateSelectedDateTitle() {
            document.getElementById('selected-date-title').textContent = 
                `${selectedDate.getFullYear()}年${selectedDate.getMonth() + 1}月${selectedDate.getDate()}日 的日程`;
        }
        
        // 渲染日程列表
        function renderSchedules(date) {
            const dateStr = formatDate(date);
            const scheduleList = document.getElementById('schedule-list');
            const dateSchedules = schedules[dateStr] || [];
            if (dateSchedules.length === 0) {
                scheduleList.innerHTML = '<div class="empty-state">暂无日程安排</div>';
                return;
            }
            
            // 按时间排序
            dateSchedules.sort((a, b) => (a.updateTime || a.createTime).localeCompare(b.updateTime || b.createTime));
            
            scheduleList.innerHTML = '';
            dateSchedules.forEach((schedule, index) => {
                const scheduleItem = document.createElement('div');

                scheduleItem.setAttribute('onclick', '$.modal.openTab("#' + schedule.id + '","/project/issue/' + schedule.id + '")');

                const priority = schedule.priority;
                const priorityClass = priority.listClass || 'primary';
                scheduleItem.className = 'schedule-item borL-' + priorityClass;

                const issueStatus = schedule.issueStatus;
                const statusColor = issueStatus ? (issueStatus.htmlColor || 'primary') : 'primary';
                
                // 使用 schedule.content 作为默认值，避免 undefined
                const title = schedule.title || schedule.content;
                const desc = schedule.desc || '';
                
                scheduleItem.innerHTML = `
                    <div class="time">
                        <div class="tracker-name col-${priorityClass}">${schedule.trackerName}#${schedule.id}</div>
                        <div class="badge badge-${statusColor}">${schedule.statusName}</div>
                    </div>
                    <div class="content">
                        <div class="schedule-title">${schedule.projectName}</div>
                        <div class="schedule-content">${schedule.subject}</div>
                    </div>
                `;
                scheduleList.appendChild(scheduleItem);
            });
            
            // 添加编辑和删除事件监听
            document.querySelectorAll('.action-btn.edit').forEach(btn => {
                btn.addEventListener('click', function() {
                    editSchedule(this.getAttribute('data-id'));
                });
            });
            
            document.querySelectorAll('.action-btn.delete').forEach(btn => {
                btn.addEventListener('click', function() {
                    deleteSchedule(this.getAttribute('data-id'));
                });
            });
        }
        
        // 上个月
        function prevMonth() {
            currentViewDate.setMonth(currentViewDate.getMonth() - 1);
			// 仅当参数日期小于等于当前日期时执行查询
			var currentDate = new Date();
			var viewDate = new Date(currentViewDate);
			if (viewDate <= currentDate) {
				queryIssueList(currentViewDate);
			}else{
                renderCalendar(currentViewDate);
            }
        }
        
        // 下个月
        function nextMonth() {
            currentViewDate.setMonth(currentViewDate.getMonth() + 1);
			// 仅当参数日期小于等于当前日期时执行查询
			var currentDate = new Date();
			var viewDate = new Date(currentViewDate);
			if (viewDate <= currentDate) {
				queryIssueList(currentViewDate);
			}else{
                renderCalendar(currentViewDate);
            }
        }
        
        // 回到今天
        function goToToday() {
            const today = new Date();
            currentViewDate = new Date(today.getFullYear(), today.getMonth(), 1);
            selectedDate = today;
			// 仅当参数日期小于等于当前日期时执行查询
			var currentDate = new Date();
			var viewDate = new Date(currentViewDate);
			if (viewDate <= currentDate) {
				queryIssueList(currentViewDate);
			}
            renderCalendar(currentViewDate);
            renderSchedules(today);
            updateSelectedDateTitle();
        }
        
        // 打开添加日程模态框
        function openAddSchedule() {
            editingScheduleId = null;
            document.getElementById('modal-title').textContent = '添加日程';
            document.getElementById('schedule-date').value = formatDate(selectedDate, 'input');
            document.getElementById('schedule-time').value = '09:00';
            document.getElementById('schedule-content').value = '';
            document.getElementById('schedule-important').checked = false;
            document.getElementById('schedule-modal').style.display = 'flex';
        }
        
        // 关闭模态框
        function closeModal() {
            document.getElementById('schedule-modal').style.display = 'none';
        }
        function closeModalList() {
            document.getElementById('schedule-modal-list').style.display = 'none';
        }
        
        // 编辑日程
        function editSchedule(scheduleId) {
            const [dateStr, index] = scheduleId.split('-');
            const schedule = schedules[dateStr][parseInt(index)];
            
            editingScheduleId = scheduleId;
            document.getElementById('modal-title').textContent = '编辑日程';
            document.getElementById('schedule-date').value = dateStr.replace(/(\d{4})-(\d{1,2})-(\d{1,2})/, '$1-$2-$3');
            document.getElementById('schedule-time').value = schedule.time;
            document.getElementById('schedule-content').value = schedule.content;
            document.getElementById('schedule-important').checked = schedule.important || false;
            document.getElementById('schedule-modal').style.display = 'flex';
        }
        
        // 删除日程
        function deleteSchedule(scheduleId) {
            if (confirm('确定要删除这个日程吗？')) {
                const [dateStr, index] = scheduleId.split('-');
                schedules[dateStr].splice(parseInt(index), 1);
                
                // 如果当天没有日程了，删除该日期键
                if (schedules[dateStr].length === 0) {
                    delete schedules[dateStr];
                }
                
                // 保存到本地存储
                localStorage.setItem('schedules', JSON.stringify(schedules));
                
                // 更新界面
                renderSchedules(selectedDate);
                renderCalendar(currentViewDate);
            }
        }
        
        // 保存日程
        function saveSchedule() {
            const date = document.getElementById('schedule-date').value;
            const time = document.getElementById('schedule-time').value;
            const content = document.getElementById('schedule-content').value.trim();
            const important = document.getElementById('schedule-important').checked;
            
            if (!date || !time || !content) {
                alert('请填写日期、时间和日程内容');
                return;
            }
            
            // 格式化日期字符串
            const dateParts = date.split('-');
            const dateStr = `${dateParts[0]}-${parseInt(dateParts[1])}-${parseInt(dateParts[2])}`;
            
            if (!schedules[dateStr]) {
                schedules[dateStr] = [];
            }
            
            if (editingScheduleId) {
                // 编辑现有日程
                const [oldDateStr, index] = editingScheduleId.split('-');
                const oldIndex = parseInt(index);
                
                // 如果日期改变了，需要从原日期删除，添加到新日期
                if (oldDateStr !== dateStr) {
                    const schedule = schedules[oldDateStr][oldIndex];
                    schedules[oldDateStr].splice(oldIndex, 1);
                    
                    // 如果原日期没有日程了，删除该日期键
                    if (schedules[oldDateStr].length === 0) {
                        delete schedules[oldDateStr];
                    }
                    
                    schedules[dateStr].push({
                        time: time,
                        content: content,
                        important: important
                    });
                } else {
                    // 同一日期内编辑
                    schedules[dateStr][oldIndex] = {
                        time: time,
                        content: content,
                        important: important
                    };
                }
            } else {
                // 添加新日程
                schedules[dateStr].push({
                    time: time,
                    content: content,
                    important: important
                });
            }
            
            // 保存到本地存储
            localStorage.setItem('schedules', JSON.stringify(schedules));
            
            // 更新界面
            if (dateStr === formatDate(selectedDate)) {
                renderSchedules(selectedDate);
            }
			renderDayEvents(selectedDate);
            
            renderCalendar(currentViewDate);
            closeModal();
        }
        
        // 工具函数：格式化日期为YYYY-M-D
        function formatDate(date, type = 'string') {
            if (type === 'input') {
                // 用于input[type=date]的格式YYYY-MM-DD
                return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
            }
            return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
        }
        
        // 工具函数：判断两个日期是否是同一天
        function isSameDay(date1, date2) {
            return date1.getFullYear() === date2.getFullYear() &&
                   date1.getMonth() === date2.getMonth() &&
                   date1.getDate() === date2.getDate();
        }


		// 预览报表数据
		function queryIssueList(viewDate) {
            var checkDate = formatDate(viewDate)
		    $.modal.loading("正在加载预览数据...");
		    
		    $.ajax({
		        url: ctx + "my/workbench/queryIssueList",
		        type: "get",
		        data: {
		        	'checkDate': checkDate
				},
		        success: function(result) {
		            $.modal.closeLoading();
		            if (result.code == 0) {
                        issueData = result.data;
                        schedules = JSON.parse(issueData) || {};
                        renderCalendar(viewDate);
                        renderDayEvents(viewDate)
		            } else {
		                $.modal.alert(result.msg || '获取预览数据失败');
		            }
		        },
		        error: function() {
		            $.modal.closeLoading();
		            $.modal.alert('获取预览数据失败，请检查网络连接');
		        }
		    });
		}
    </script>
</body>
</html>